<template>
  <a-modal
    :title="title"
    :visible="visible"
    @ok="handleSubmit"
    @cancel="close"
  >
    <a-form-model
      ref="form"
      :model="form"
      :rules="rules"
      v-bind="formItemLayout"
      @submit="handleSubmit"
    >
      <a-form-model-item label="名称" prop="menuName">
        <a-input v-model="form.menuName" />
      </a-form-model-item>
      <a-form-model-item label="类型" prop="menuType">
        <a-radio-group v-model="form.menuType">
          <a-radio-button value="MENU">
            菜单
          </a-radio-button>
          <a-radio-button value="BUTTON">
            按钮
          </a-radio-button>
        </a-radio-group>
      </a-form-model-item>

      <a-form-model-item label="图标">
        <a-input
          v-model="form.menuIcon"
        />
      </a-form-model-item>
      <a-form-model-item label="地址">
        <a-input
          v-model="form.href"
        />
      </a-form-model-item>
      <a-form-model-item label="权限">
        <a-input
          v-model="form.permission"
        />
      </a-form-model-item>

      <a-form-model-item label="是否显示">
        <a-switch
          v-model="form.show"
        />
      </a-form-model-item>

      <a-form-model-item label="排序">
        <a-input
          v-model="form.sort"
        />
      </a-form-model-item>
    </a-form-model>
  </a-modal>
</template>

<script>
import {saveMenu} from '@/api/menu'

export default {

  data() {
    return {
      form: {
        menuName: '',
        menuType: '',
        menuIcon: '',
        href: '',
        permission: '',
        show: '',
        sort: ''
      },
      rules: {
        menuName: [
          {required: true, message: '请输入名称', trigger: 'blur'}
        ],
        menuType: [
          {required: true, message: '请选择类型', trigger: 'blur'}
        ]
      },
      visible: false,
      title: '',
      formItemLayout: {
        labelCol: {span: 6},
        wrapperCol: {span: 14}
      }
    }
  },
  methods: {
    initData(form) {
      this.visible = true
      this.form = form
      this.form.menuName == null ? this.title = '新建' : this.title = '编辑'
    },
    handleSubmit() {
      this.$refs.form.validate(v => {
        if (v) {
          if (!this.form.id) this.form.createUser = this.$store.getters.id
          this.form.modifyUser = this.$store.getters.id
          saveMenu(this.form).then(res => {
            if (res.code === '0') {
              this.$message.success('保存成功')
              this.close()
            } else {
              this.$message.error(res.message)
            }
          }).catch(error => {
            if (error.response) {
              this.$message.error(error.response.message)
            }
          })
        }
      })
    },
    close() {
      this.visible = false
      this.$emit('close')
    }
  }
}
</script>
<style>
  #components-form-demo-validate-other .dropbox {
    height: 180px;
    line-height: 1.5;
  }
</style>
